import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;

class DataVault {
  static final DataVault _singleton = DataVault._private();
  factory DataVault() => _singleton;
  DataVault._private();

  Future<Directory> get _rootStorage async {
    return await getApplicationDocumentsDirectory();
  }

  Future<Directory> get _mediaCache async {
    final baseDir = await _rootStorage;
    final targetDir = Directory(path.join(baseDir.path, 'media_vault'));
    if (!await targetDir.exists()) {
      await targetDir.create(recursive: true);
    }
    return targetDir;
  }

  Future<String?> storeAsset(String sourcePath, String identifier) async {
    try {
      final sourceFile = File(sourcePath);
      if (!await sourceFile.exists()) {
        return null;
      }

      final extension = path.extension(sourcePath);
      final targetDir = await _mediaCache;
      final targetPath = path.join(targetDir.path, '$identifier$extension');

      await sourceFile.copy(targetPath);
      return targetPath;
    } catch (e) {
      return null;
    }
  }

  String buildTimeStamp(DateTime date) {
    return 'record_${date.year}${date.month.toString().padLeft(2, '0')}${date.day.toString().padLeft(2, '0')}';
  }
}
